import config from "@/config";

// #ifdef APP-NVUE
import uniRequest from "uni-request";
uniRequest.defaults.baseURL = config.BASE_API_URL;
export default uniRequest;
// #endif

// #ifndef APP-PLUS-NVUE
import wx from "flyio/dist/npm/wx";
import store from "@/store";

import uniApp from "@/utils/uni-app";
import Vue from "vue";
const fly = new wx();

fly.config.baseURL = config.BASE_API_URL;
fly.config.withCredentials = true;
fly.config.timeout = 15000;
// 请求拦截器
fly.interceptors.request.use(config => {
  if (store.state.user.TOKEN) {
      config.headers = { ...config.headers,
        'Content-Type': 'application/json',
        Authorization: store.state.user.TOKEN
      };
    }
  return config;
}, (error, promise) => {
  console.warn("request.error", error);
  return promise.reject(error);
});
// 响应拦截器
fly.interceptors.response.use(response => {
  if (response.status === 200) {
    if (response.data.error === 0) {
      return response;
    } else if (response.data.error === 1) {
      return Promise.reject(response);
    } else if (response.data.error === 1002) {
      store.commit("user/LOGOUT");
      uni.showModal({
        title: "提示",
        content: "您尚未登录或登录已过期",
        confirmText: "去登录",
        cancelText: "返回",
        success: res => {
          if (res.confirm) {
            uni.navigateTo({
              url: "/pages/common/login"
            });
          }
        }
      });
      return Promise.reject(response);
    } else if (response.data.error === 1003) {
      // 账户冻结
      uni.showModal({
        title: "提示",
        content: response.data.msg,
        confirmText: "确定",
        showCancel: false,
        success: res => {

        }
      });
    }
  } else if (response.status === 405) {
    uniApp.alert("请求的方法不被允许");
    return false;
  } else {
    return Promise.reject(response);
  }
}, (error, promise) => {
  console.warn("response.error", error);
  if (error.status === 0) {
    return promise.reject(new Error("网络错误,请稍后再试!"));
  }
  if (error.status === 1) {
    return promise.reject(new Error("请求超时,请稍后再试!"));
  }
  return promise.reject(new Error("请求服务失败,请稍后再试!"));
});

export default fly;
// #endif